package safeCommitter.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class FileUtils {

	private static final int DEFAULT_BUFFER_SIZE = 1024 * 4;

	public static String readFileToString(final File f) throws IOException {
		Reader input = new FileReader(f);
		StringWriter sw = new StringWriter();
		copy(input, sw);
		return sw.toString();

	}

	private static int copy(final Reader input, final Writer output)
			throws IOException {
		char[] buffer = new char[DEFAULT_BUFFER_SIZE];
		int count = 0;
		int n = 0;
		while (-1 != (n = input.read(buffer))) {
			output.write(buffer, 0, n);
			count += n;
		}
		return count;
	}

	public static void writeStringToFile(final File file, final String data)
			throws IOException {
		OutputStream out = null;
		try {
			out = openOutputStream(file);
			write(data, out, null);
		} finally {
			closeQuietly(out);
		}
	}

	public static void write(final String data, final OutputStream output,
			final String encoding) throws IOException {
		if (data != null) {
			if (encoding == null) {
				write(data, output);
			} else {
				output.write(data.getBytes(encoding));
			}
		}
	}

	public static FileOutputStream openOutputStream(final File file)
			throws IOException {
		if (file.exists()) {
			if (file.isDirectory()) {
				throw new IOException("File '" + file
						+ "' exists but is a directory");
			}
			if (file.canWrite() == false) {
				throw new IOException("File '" + file
						+ "' cannot be written to");
			}
		} else {
			File parent = file.getParentFile();
			if (parent != null && parent.exists() == false) {
				if (parent.mkdirs() == false) {
					throw new IOException("File '" + file
							+ "' could not be created");
				}
			}
		}
		return new FileOutputStream(file);
	}

	public static void write(final String data, final OutputStream output)
			throws IOException {
		if (data != null) {
			output.write(data.getBytes());
		}
	}

	public static void closeQuietly(final OutputStream output) {
		try {
			if (output != null) {
				output.close();
			}
		} catch (IOException ioe) {
			// ignore
		}
	}

}
